package com.itheima.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;


    @RequestMapping("/login")
    public Result login(@RequestBody Map map, HttpServletResponse response){
        String telephone = (String) map.get("telephone");
        //获取前台输入的验证码
        String validateCode = (String) map.get("validateCode");

        String validateCodeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);

        if(validateCode == null){
            //未输入验证码
            return new Result(false, MessageConstant.TELEPHONE_VALIDATECODE_NOTNULL);
        }

        if(validateCodeInRedis == null){
            //redis数据库中无此数据，或者时间到了删除了
            return new Result(false, MessageConstant.VALIDATE_DISABLED);
        }
        if(!validateCodeInRedis.equals(validateCode)){
            //验证码不正确
            return new Result(false,MessageConstant.VALIDATECODE_ERROR);
        }

        //如果走到这里，说明验证码验证没有问题
        //此时登录，需要看该手机号码是否已成为用户
        Member member = memberService.findByTelephone(telephone);
        if(member == null){
            //此用户不存在，直接创建用户
            member = new Member();
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            memberService.addMember(member);
        }

        //此时将telephone利用cookie技术，回写到浏览器
        //这样浏览器在后面的访问时，就会带着telephone，这样就直接可以验证身份
        Cookie cookie = new Cookie("login_member_telephone", telephone);
        //这个/表示访问当前网页的当前主机名，后面只要还是访问当前主机下的路径，都会携带此cookie
        //如果不设置此值，系统回给默认值，表示www.itheima.com/mobile，只表示此路径下的才会携带此cookie
        cookie.setPath("/");
        cookie.setMaxAge(60*60*24*30);
        response.addCookie(cookie);

        //再将用户的数据放入到redis数据库中
        String json = JSON.toJSON(member).toString();
        jedisPool.getResource().setex("member",60*30,json);
        return new Result(true,MessageConstant.LOGIN_SUCCESS);
    }
}
